package problems.daily.y2022m8;

/**
 * 640. 求解方程
 * https://leetcode.cn/problems/solve-the-equation/
 *
 * @author habitplus
 * @since 2022/8/10 13:54
 */
public class D20220810_640 {
    public String solveEquation(String eq) {
        if (eq == null || eq.length() < 3) return "No solution";
        int k = eq.indexOf("=");
        int[] l = solve(eq.substring(0, k));
        int[] r = solve(eq.substring(k + 1, eq.length()));

        if (l[0] == r[0]) return l[1] == r[1] ? "Infinite Solutions" : "No Solution";
        else return "x=" + (r[1] - l[1]) / (l[0] - r[0]);
    }

    private int[] solve(String s) {
        if (s == null || s.length() < 1) return new int[]{0, 0};
        // 常数项
        int numSum = 0;
        // x 的系数
        int xSum = 0;

        int i = 0;
        int n = s.length();
        char[] chs = s.toCharArray();

        // 标记是否为 x 的系数
        boolean xFlag;
        int t;
        int fh = 1;
        int j;

        while (i < n) {
            xFlag = false;
            t = 0;
            j = i;
            while ((i < n) && (chs[i] != '+' && chs[i] != '-')) {
                if ('0' <= chs[i] && chs[i] <= '9') {
                    t = t * 10 + (chs[i] - '0');
                } else if (chs[i] == 'x') {
                    xFlag = true;
                }
                i++;
            }

            if (xFlag) {
                // x 的系数
                if (i - j > 1) // x 前面有系数
                    xSum += t * fh;
                else xSum += fh;
            } else {
                numSum += t * fh;
            }
            if (i < n) fh = chs[i] == '-' ? -1 : 1;
            i++;
        }

        return new int[]{xSum, numSum};

    }

    public static void main(String[] args) {
        System.out.println(new D20220810_640().solveEquation("x+5-3+x=6+x-2"));
        System.out.println(new D20220810_640().solveEquation("x=x"));
        System.out.println(new D20220810_640().solveEquation("2x=x"));
    }
}
